package dbinit;

import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import core.attribute.model.Attribute;
import core.attribute.model.AttributeSet;
import core.attribute.model.AttributeValue;
import core.product.model.Product;
import core.product.model.ProductAv;
import core.util.HibernateCoreUtil;

public class InitProductAv 
{
	public static ProductAv getProductAv(Product product,AttributeSet attributeSet,Attribute attribute)
	{
		ProductAv pav = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try
		{
			transaction = session.beginTransaction(); 
			List <ProductAv> pas = session.createQuery("from ProductAv pav where pav.product=:p and pav.attributeSet=:as and pav.attribute=:a").setEntity("p",product).setEntity("as", attributeSet).setEntity("a", attribute).list();
		    if(pas.size() > 0)
		    {
		    	pav = pas.get(0);
		    }
			 transaction.commit();
		}
		catch(HibernateException e)
		{
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return pav ;
	}
	public static Long doinit(Product product,AttributeSet attributeSet,Attribute attribute,Set<AttributeValue> attributeValues,String value)
	{
		Long uuid = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		ProductAv pav = getProductAv(product, attributeSet, attribute) ;
		if(pav == null)
		{
			pav = new ProductAv();
		}
		try
		{
			transaction = session.beginTransaction(); 
			pav.setProduct(product);
			pav.setAttributeSet(attributeSet);
			pav.setAttribute(attribute);
			if(attribute.isMultivalued())
			{
				pav.setAttributeValues(attributeValues);
			}
			else
			{
				pav.setValue(value);
			}
			session.saveOrUpdate(pav); 
			uuid = pav.getUuid();
		    transaction.commit();
		}
		catch(HibernateException e)
		{
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return uuid ;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		// TODO Auto-generated method stub
		
	}

}
